package com.ruoyi.system.service.impl;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.StopMapper;
import com.ruoyi.system.domain.Stop;
import com.ruoyi.system.service.IStopService;

/**
 * 停服表Service业务层处理
 * 
 * @author zhangkai
 * @date 2021-11-24
 */
@Service
public class StopServiceImpl implements IStopService 
{
	private static final Logger log = LoggerFactory.getLogger(StopServiceImpl.class);
    @Autowired
    private StopMapper stopMapper;

    /**
     * 查询停服表
     * 
     * @param id 停服表主键
     * @return 停服表
     */
    @Override
    public Stop selectStopById(Long id)
    {
        return stopMapper.selectStopById(id);
    }

    /**
     * 查询停服表列表
     * 
     * @param stop 停服表
     * @return 停服表
     */
    @Override
    public List<Stop> selectStopList(Stop stop)
    {
        return stopMapper.selectStopList(stop);
    }

    /**
     * 新增停服表
     * 
     * @param stop 停服表
     * @return 结果
     */
    @Override
    public int insertStop(Stop stop)
    {
        stop.setCreateTime(DateUtils.getNowDate());
        return stopMapper.insertStop(stop);
    }

    /**
     * 修改停服表
     * 
     * @param stop 停服表
     * @return 结果
     */
    @Override
    public int updateStop(Stop stop)
    {
        stop.setUpdateTime(DateUtils.getNowDate());
        return stopMapper.updateStop(stop);
    }

    /**
     * 批量删除停服表
     * 
     * @param ids 需要删除的停服表主键
     * @return 结果
     */
    @Override
    public int deleteStopByIds(Long[] ids)
    {
        return stopMapper.deleteStopByIds(ids);
    }

    /**
     * 删除停服表信息
     * 
     * @param id 停服表主键
     * @return 结果
     */
    @Override
    public int deleteStopById(Long id)
    {
        return stopMapper.deleteStopById(id);
    }
    
    /**
     * 导入全站数据
     * 
     * @param totalList 全站数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importTotal(List<Stop> totalList,String operName,String dateRange)
    {
    	if(dateRange.equals("null")) {
    		throw new ServiceException("版本不能为空！");
    	}
    	String newDateRange = dateRange.replaceAll("-", "").replaceAll(":", "").replaceAll(" ", "").substring(0,12);
        if (StringUtils.isNull(totalList) || totalList.size() == 0)
        {
            throw new ServiceException("导入关键站址数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Stop site : totalList)
        {
            try
               {
            	    site.setVersion(newDateRange);
                    this.insertStop(site);
                    successNum++;
                  //  successMsg.append("<br/>" + successNum + "、站址编码: " + site.getStationCode() + " 导入成功");
                }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、站址编码: " + site.getStationCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    
    /* 缓存初始化 */
    private LoadingCache<String, String> maxCache = CacheBuilder.newBuilder().maximumSize(1000)
            .build(new CacheLoader<String, String>() {
                /* 加载缓存方法 */
                public String load(String key) throws InterruptedException {
                    /* 返回 */
                    return stopMapper.maxVersion();
                }
            });
    
	@Override
	public String maxVersion() {
		try {
            /* 调用缓存 */
            return maxCache.get("");
        } catch (ExecutionException e) {
            /* 记录日志 */
        	log.error(e.getMessage(), e);
        }
        /* 异常返回空 */
        return null;
	}
	
	@Override
	public void cacheClean() {
		maxCache.invalidateAll();
	}
}
